package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.common.util.PageResult;
import com.qk.domain.clue.ClueDO;
import com.qk.domain.clue.ClueFollowDto;
import com.qk.dto.clue.ClueDto;
import com.qk.dto.clue.ClueListDto;
import com.qk.dto.clue.CluePoolDto;
import com.qk.entity.Business;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.entity.User;
import com.qk.management.constant.BusinessStatusConstants;
import com.qk.management.constant.ClueStatusConstants;
import com.qk.management.constant.ClueTrackRecordType;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.ClueTrackRecordMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.ClueService;
import com.qk.vo.ClueVO;
import com.qk.vo.clue.CluePoolVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


@Slf4j
@Service
@SuppressWarnings("all")
@Transactional(rollbackFor = Exception.class)
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;
    @Autowired
    private BusinessMapper businessMapper;



    @Override
    public void addClue(ClueDto clueDto) {
        boolean b = BeanUtil.hasNullField(clueDto, "acticityId", "name","gender","age","wechat","qq");
//        if(ObjectUtil.isEmpty(clueDto.getPhone())||ObjectUtil.isEmpty(clueDto.getChannel())){
        if(b) {   CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Clue clue = BeanUtil.toBean(clueDto, Clue.class);
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstants.WAIT_ALLOCATION);
        this.baseMapper.insert(clue);
    }

    @Override
    public PageResult<ClueDO> list(ClueListDto clueListDto) {
        PageHelper.startPage(clueListDto.getPage(), clueListDto.getPageSize());
        Page<ClueDO> page = this.baseMapper.querylist(clueListDto);
        return PageResult.<ClueDO>builder()
                .total((int)page.getTotal())
                .rows(page)
                .build();

    }
    @Override
    public ClueVO getClueById(Integer id) {
        Clue clue =this.baseMapper.selectById(id);
        Integer userId = clue.getUserId();
        User user = userMapper.selectById(userId);
        List<ClueTrackRecord> clueTrackRecords = clueTrackRecordMapper.selectList(Wrappers.lambdaQuery(ClueTrackRecord.class).eq(ClueTrackRecord::getClueId, id));
        ClueVO clueVO = BeanUtil.copyProperties(clue, ClueVO.class);
        List<ClueVO.ClueTrackRecordVO> list = clueTrackRecords.stream().map(item -> {
            ClueVO.ClueTrackRecordVO clueTrackRecordVO = BeanUtil.copyProperties(item, ClueVO.ClueTrackRecordVO.class);
            clueTrackRecordVO.setAssignName(user.getName());
            return clueTrackRecordVO;
         }).toList();
        clueVO.setTrackRecords(list);
        return clueVO;
    }

    @Override
    public void updateClueById(ClueFollowDto cfd) {
        // 更新线索
        Clue clue = BeanUtil.copyProperties(cfd, Clue.class);
        clue.setUpdateTime(LocalDateTime.now());
        if(cfd.getStatus()==ClueStatusConstants.WAIT_FOLLOW_UP){
            clue.setStatus(ClueStatusConstants.FOLLOW_UP);
        }
        this.baseMapper.updateById(clue);
        // 添加线索跟进记录
        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(cfd, ClueTrackRecord.class);
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecord.setId(null);
        clueTrackRecord.setClueId(clue.getId());
        clueTrackRecord.setType(ClueTrackRecordType.NORMAL);
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        this.clueTrackRecordMapper.insert(clueTrackRecord);
    }

    @Override
    public void toBusiness(Integer id) {
        Clue clue = this.baseMapper.selectById(id);
        clue.setStatus(ClueStatusConstants.CONVERT_TO_BUSINESS);
        clue.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(clue);
        Business business = BeanUtil.copyProperties(clue, Business.class);
        business.setId(null);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setNextTime(null);
        business.setUserId(null);
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        business.setClueId(id);
        this.businessMapper.insert(business);
    }

    @Override
    public PageResult<CluePoolVo> pool(CluePoolDto cpd) {
        PageHelper.startPage(cpd.getPage(), cpd.getPageSize());
        Page<CluePoolVo> page = this.baseMapper.pool(cpd);
        return PageResult.<CluePoolVo>builder()
                .total((int)page.getTotal())
                .rows(page)
                .build();
    }

}
